// JavaScript相关功能实现

use super::app::FeatureTester;
use super::types::{JsLog, JsLogLevel}; // 导入 types 模块中的类型
use eframe::egui;

impl FeatureTester {
    // JS交互标签页
    pub fn render_js_interaction_tab(&mut self, ui: &mut egui::Ui) {
        ui.heading("JavaScript交互");

        ui.add_space(10.0);
        ui.horizontal(|ui| {
            ui.vertical(|ui| {
                ui.label("HTML内容:");
                ui.add(
                    egui::TextEdit::multiline(&mut self.html_input)
                        .desired_width(ui.available_width() * 0.48)
                        .desired_rows(10),
                );
            });

            ui.vertical(|ui| {
                ui.label("JavaScript代码:");
                ui.add(
                    egui::TextEdit::multiline(&mut self.js_input)
                        .desired_width(ui.available_width())
                        .desired_rows(10),
                );
            });
        });

        ui.add_space(10.0);
        ui.collapsing("执行选项", |ui| {
            ui.checkbox(&mut self.js_execution_in_dom, "在DOM环境中执行");
            ui.checkbox(&mut self.js_allow_network, "允许网络请求");
            ui.checkbox(&mut self.js_console_log, "启用控制台输出");
            ui.checkbox(&mut self.js_strict_mode, "严格模式");

            ui.horizontal(|ui| {
                ui.label("最大执行时间:");
                ui.add(egui::Slider::new(&mut self.js_execution_timeout, 100..=10000).text("ms"));
            });
        });

        ui.add_space(10.0);
        ui.horizontal(|ui| {
            if ui.button("执行JavaScript").clicked() {
                self.execute_javascript();
            }

            if ui.button("清除结果").clicked() {
                self.js_execution_result = String::new();
                self.js_console_output.clear();
            }
        });

        ui.add_space(10.0);
        ui.label("执行结果:");
        ui.add(
            egui::TextEdit::multiline(&mut self.js_execution_result)
                .desired_width(f32::INFINITY)
                .desired_rows(8)
                .frame(true)
                .interactive(false),
        );

        if !self.js_console_output.is_empty() {
            ui.add_space(10.0);
            ui.label("控制台输出:");
            egui::ScrollArea::vertical()
                .max_height(150.0)
                .show(ui, |ui| {
                    for (idx, log) in self.js_console_output.iter().enumerate() {
                        ui.horizontal(|ui| {
                            let log_type = match log.level {
                                JsLogLevel::Info => "INFO",
                                JsLogLevel::Warning => "WARN",
                                JsLogLevel::Error => "ERROR",
                            };

                            let log_color = match log.level {
                                JsLogLevel::Info => egui::Color32::from_rgb(42, 157, 143),
                                JsLogLevel::Warning => egui::Color32::from_rgb(233, 196, 106),
                                JsLogLevel::Error => egui::Color32::from_rgb(231, 111, 81),
                            };

                            ui.label(
                                egui::RichText::new(format!("[{}]", log_type)).color(log_color),
                            );
                            ui.label(&log.message);
                        });

                        if idx < self.js_console_output.len() - 1 {
                            ui.separator();
                        }
                    }
                });
        }

        ui.add_space(10.0);
        ui.collapsing("DOM预览", |ui| {
            if self.js_execution_in_dom && !self.js_execution_result.is_empty() {
                ui.label("执行JavaScript后的DOM结构:");

                let (rect, _) = ui.allocate_exact_size(
                    egui::vec2(ui.available_width(), 200.0),
                    egui::Sense::hover(),
                );

                // 简单模拟执行JavaScript后的DOM预览
                ui.painter()
                    .rect_filled(rect, 4.0, egui::Color32::from_rgb(245, 245, 245));

                let dom_preview = if self.js_execution_result.contains("已加载") {
                    "修改后的DOM: h1元素文本被修改为 '测试HTML - 已加载'"
                } else {
                    "DOM结构未发生变化"
                };

                ui.painter().text(
                    rect.center(),
                    egui::Align2::CENTER_CENTER,
                    dom_preview,
                    egui::FontId::proportional(16.0),
                    egui::Color32::BLACK,
                );
            } else {
                ui.label("需要开启 '在DOM环境中执行' 并执行JavaScript才能显示DOM预览");
            }
        });
    }

    // DOM事件标签页
    pub fn render_dom_events_tab(&mut self, ui: &mut egui::Ui) {
        ui.heading("DOM事件测试");

        ui.add_space(10.0);
        ui.horizontal(|ui| {
            ui.vertical(|ui| {
                ui.label("HTML内容:");
                ui.add(
                    egui::TextEdit::multiline(&mut self.html_input)
                        .desired_width(ui.available_width() * 0.48)
                        .desired_rows(10),
                );
            });

            ui.vertical(|ui| {
                ui.label("事件处理JavaScript:");
                ui.add(
                    egui::TextEdit::multiline(&mut self.js_input)
                        .desired_width(ui.available_width())
                        .desired_rows(10),
                );
            });
        });

        ui.add_space(10.0);
        ui.collapsing("可用事件类型", |ui| {
            egui::Grid::new("events_grid")
                .num_columns(2)
                .spacing([40.0, 4.0])
                .striped(true)
                .show(ui, |ui| {
                    ui.strong("鼠标事件");
                    ui.strong("键盘事件");
                    ui.end_row();

                    ui.label("click");
                    ui.label("keydown");
                    ui.end_row();

                    ui.label("dblclick");
                    ui.label("keyup");
                    ui.end_row();

                    ui.label("mousedown");
                    ui.label("keypress");
                    ui.end_row();

                    ui.label("mouseup");
                    ui.strong("表单事件");
                    ui.end_row();

                    ui.label("mousemove");
                    ui.label("submit");
                    ui.end_row();

                    ui.label("mouseover");
                    ui.label("reset");
                    ui.end_row();

                    ui.label("mouseout");
                    ui.label("change");
                    ui.end_row();

                    ui.strong("文档/窗口事件");
                    ui.label("focus");
                    ui.end_row();

                    ui.label("load");
                    ui.label("blur");
                    ui.end_row();

                    ui.label("resize");
                    ui.strong("拖拽事件");
                    ui.end_row();

                    ui.label("scroll");
                    ui.label("dragstart");
                    ui.end_row();

                    ui.label("DOMContentLoaded");
                    ui.label("dragover");
                    ui.end_row();
                });
        });

        ui.add_space(10.0);
        ui.collapsing("事件模拟", |ui| {
            ui.horizontal(|ui| {
                ui.label("目标元素选择器:");
                ui.text_edit_singleline(&mut self.event_target_selector);
            });

            ui.horizontal(|ui| {
                ui.label("事件类型:");
                egui::ComboBox::from_id_source("event_type")
                    .selected_text(self.selected_event_type.clone())
                    .show_ui(ui, |ui| {
                        ui.selectable_value(
                            &mut self.selected_event_type,
                            "click".to_string(),
                            "click",
                        );
                        ui.selectable_value(
                            &mut self.selected_event_type,
                            "mousedown".to_string(),
                            "mousedown",
                        );
                        ui.selectable_value(
                            &mut self.selected_event_type,
                            "mouseup".to_string(),
                            "mouseup",
                        );
                        ui.selectable_value(
                            &mut self.selected_event_type,
                            "keydown".to_string(),
                            "keydown",
                        );
                        ui.selectable_value(
                            &mut self.selected_event_type,
                            "change".to_string(),
                            "change",
                        );
                        ui.selectable_value(
                            &mut self.selected_event_type,
                            "submit".to_string(),
                            "submit",
                        );
                        ui.selectable_value(
                            &mut self.selected_event_type,
                            "load".to_string(),
                            "load",
                        );
                    });
            });

            if self.selected_event_type == "keydown" || self.selected_event_type == "keyup" {
                ui.horizontal(|ui| {
                    ui.label("按键代码:");
                    ui.text_edit_singleline(&mut self.event_key_code);
                });
            }

            if ui.button("触发事件").clicked() {
                self.trigger_dom_event();
            }
        });

        ui.add_space(10.0);
        ui.label("事件测试结果:");
        ui.add(
            egui::TextEdit::multiline(&mut self.event_test_result)
                .desired_width(f32::INFINITY)
                .desired_rows(6)
                .frame(true)
                .interactive(false),
        );

        ui.add_space(10.0);
        ui.collapsing("交互式DOM", |ui| {
            let (rect, _) = ui.allocate_exact_size(
                egui::vec2(ui.available_width(), 300.0),
                egui::Sense::click(),
            );

            // 绘制简单的DOM交互预览
            ui.painter().rect_filled(rect, 8.0, egui::Color32::WHITE);

            // 绘制模拟的DOM结构
            let title_rect = egui::Rect::from_min_size(
                egui::pos2(rect.min.x + 20.0, rect.min.y + 20.0),
                egui::vec2(rect.width() - 40.0, 40.0),
            );

            ui.painter()
                .rect_filled(title_rect, 4.0, egui::Color32::from_rgb(240, 240, 240));

            ui.painter().text(
                title_rect.center(),
                egui::Align2::CENTER_CENTER,
                "测试HTML",
                egui::FontId::proportional(24.0),
                egui::Color32::BLACK,
            );

            let paragraph_rect = egui::Rect::from_min_size(
                egui::pos2(rect.min.x + 20.0, title_rect.max.y + 20.0),
                egui::vec2(rect.width() - 40.0, 60.0),
            );

            ui.painter()
                .rect_filled(paragraph_rect, 4.0, egui::Color32::from_rgb(245, 245, 245));

            ui.painter().text(
                paragraph_rect.center(),
                egui::Align2::CENTER_CENTER,
                "这是一个测试段落。",
                egui::FontId::proportional(16.0),
                egui::Color32::BLACK,
            );

            let image_rect = egui::Rect::from_min_size(
                egui::pos2(rect.min.x + 40.0, paragraph_rect.max.y + 20.0),
                egui::vec2(120.0, 120.0),
            );

            ui.painter()
                .rect_filled(image_rect, 4.0, egui::Color32::LIGHT_BLUE);

            ui.painter().text(
                image_rect.center(),
                egui::Align2::CENTER_CENTER,
                "测试图片",
                egui::FontId::proportional(14.0),
                egui::Color32::BLACK,
            );

            // 检查点击
            let response = ui.interact(rect, ui.id().with("dom_interact"), egui::Sense::click());
            if response.clicked() {
                let pointer_pos = ui.ctx().pointer_interact_pos().unwrap_or(egui::Pos2::ZERO);

                if title_rect.contains(pointer_pos) {
                    self.event_test_result = "h1元素被点击了！".to_string();
                } else if paragraph_rect.contains(pointer_pos) {
                    self.event_test_result = "p元素被点击了！".to_string();
                } else if image_rect.contains(pointer_pos) {
                    self.event_test_result = "图片被点击了！触发了alert()函数。".to_string();
                } else {
                    self.event_test_result = "背景被点击了。".to_string();
                }
            }

            ui.painter().text(
                egui::pos2(rect.min.x + 10.0, rect.max.y - 25.0),
                egui::Align2::LEFT_CENTER,
                "点击上面的元素来测试交互",
                egui::FontId::proportional(12.0),
                egui::Color32::GRAY,
            );
        });
    }

    // JavaScript执行相关的辅助方法
    fn execute_javascript(&mut self) {
        // 在实际应用中，这里应该调用JavaScript引擎
        // 这里我们使用模拟的方式生成结果

        // 清除之前的输出
        self.js_console_output.clear();

        // 检查JavaScript代码中的一些关键模式
        let mut execution_result = String::new();
        let js_code = self.js_input.clone();

        // 模拟控制台输出
        if self.js_console_log {
            // 添加一些模拟的控制台输出
            self.js_console_output.push(JsLog {
                level: JsLogLevel::Info,
                message: "JavaScript执行开始".to_string(),
            });

            if js_code.contains("document.querySelector") {
                self.js_console_output.push(JsLog {
                    level: JsLogLevel::Info,
                    message: "选择器调用: document.querySelector()".to_string(),
                });
            }

            if js_code.contains("addEventListener") {
                self.js_console_output.push(JsLog {
                    level: JsLogLevel::Info,
                    message: "事件监听器已添加".to_string(),
                });
            }

            if js_code.contains("style.color") {
                self.js_console_output.push(JsLog {
                    level: JsLogLevel::Info,
                    message: "样式已修改: color属性".to_string(),
                });
            }

            if !self.js_allow_network && js_code.contains("fetch") {
                self.js_console_output.push(JsLog {
                    level: JsLogLevel::Error,
                    message: "网络请求被阻止: 请启用'允许网络请求'选项".to_string(),
                });
            }
        }

        // 分析并生成执行结果
        if js_code.contains("document.addEventListener") && js_code.contains("DOMContentLoaded") {
            execution_result.push_str("✓ 在DOMContentLoaded事件上成功注册了处理函数\n");
        }

        if js_code.contains("querySelector") && js_code.contains("h1") {
            execution_result.push_str("✓ 成功查询到h1元素\n");

            if js_code.contains("textContent") && js_code.contains("+=") {
                execution_result.push_str("✓ 修改了h1元素的文本内容\n");
            }

            if js_code.contains("style.color") {
                execution_result.push_str("✓ 修改了h1元素的颜色样式\n");
            }
        }

        if js_code.contains("querySelector") && js_code.contains("img") {
            execution_result.push_str("✓ 成功查询到img元素\n");

            if js_code.contains("addEventListener") && js_code.contains("click") {
                execution_result.push_str("✓ 在img元素上添加了点击事件监听器\n");

                if js_code.contains("alert") {
                    execution_result.push_str("✓ 点击事件将触发alert()函数\n");
                }
            }
        }

        if execution_result.is_empty() {
            execution_result = "JavaScript执行完成，但未检测到DOM操作。".to_string();
        } else {
            execution_result.push_str("\n执行完成：JavaScript代码已成功运行。");
        }

        // 设置执行结果
        self.js_execution_result = execution_result;

        // 添加执行完成的日志
        if self.js_console_log {
            self.js_console_output.push(JsLog {
                level: JsLogLevel::Info,
                message: format!("JavaScript执行完成，耗时: {}ms", 123), // 模拟时间
            });
        }
    }

    // DOM事件触发相关的辅助方法
    fn trigger_dom_event(&mut self) {
        // 模拟触发DOM事件
        let selector = &self.event_target_selector;
        let event_type = &self.selected_event_type;

        let mut result = String::new();

        if selector.is_empty() {
            result = "请输入目标元素选择器".to_string();
        } else {
            // 模拟各种事件类型的触发结果
            match event_type.as_str() {
                "click" => {
                    if selector.contains("img") {
                        result = format!(
                            "成功在 {} 元素上触发了click事件\n弹出警告框: '图片被点击了！'",
                            selector
                        );
                    } else if selector.contains("h1") {
                        result = format!("成功在 {} 元素上触发了click事件", selector);
                    } else {
                        result = format!(
                            "成功在 {} 元素上触发了click事件，但没有事件处理程序响应",
                            selector
                        );
                    }
                }
                "mousedown" | "mouseup" => {
                    result = format!("成功在 {} 元素上触发了{}事件", selector, event_type);
                }
                "keydown" | "keyup" => {
                    let key = if self.event_key_code.is_empty() {
                        "Enter".to_string()
                    } else {
                        self.event_key_code.clone()
                    };
                    result = format!(
                        "成功在 {} 元素上触发了{}事件，按键: {}",
                        selector, event_type, key
                    );
                }
                "change" => {
                    result = format!("成功在 {} 元素上触发了change事件", selector);
                }
                "submit" => {
                    if selector.contains("form") {
                        result = format!("成功在 {} 元素上触发了submit事件", selector);
                    } else {
                        result = format!("无法在非表单元素 {} 上触发submit事件", selector);
                    }
                }
                "load" => {
                    if selector == "window" || selector == "document" {
                        result = format!(
                            "成功在 {} 上触发了load事件\n执行了DOMContentLoaded事件处理程序",
                            selector
                        );
                    } else if selector.contains("img") {
                        result = format!("成功在 {} 元素上触发了load事件", selector);
                    } else {
                        result = format!("在 {} 上触发load事件", selector);
                    }
                }
                _ => {
                    result = format!("在 {} 元素上触发了 {} 事件", selector, event_type);
                }
            }
        }

        self.event_test_result = result;
    }
}
